package com.nlp.visualization.utils;


import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by LXM on 2017/10/26.
 *
 * @author LXM
 * @version 1.0
 * @description 一些转换的工具方法
 * @datetime 15:12
 */
public class ConvertUtils {

    static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);

    /**
     * Json 转 Map .
     *
     * @param object 传入对象
     * @return map
     */
    public static Map<String, Object> jsonToMap(Object object) {
        Map<String, Object> data = new HashMap<String, Object>();
        // 将json字符串转换成jsonObject
        JSONObject jsonObject = JSONObject.fromObject(object);
        Iterator ite = jsonObject.keys();
        // 遍历jsonObject数据,添加到Map对象
        while (ite.hasNext()) {
            String key = ite.next().toString();
            Object value = jsonObject.get(key);
            data.put(key, value);
        }
        // 或者直接将 jsonObject赋值给Map
        // data = jsonObject;
        return data;
    }

    /**
     * 使用reflect进行转换.
     * getDeclaredFields()会获取所有属性，需要过滤不需要的类型如 static final
     * 不会获取父类的属性，需要自己编码实现
     * 耗时与Introspector相比：1:100
     */
    public static Object mapToObject(Map<String, String> map, Class<?> beanClass) throws Exception {
        if (map == null || map.size() <= 0) {
            return null;
        }

        Object obj = beanClass.newInstance();
        //获取关联的所有类，本类以及所有父类
        boolean ret = true;
        Class oo = obj.getClass();
        List<Class> clazzs = new ArrayList<Class>();
        while (ret) {
            clazzs.add(oo);
            oo = oo.getSuperclass();
            if (oo == null || oo == Object.class) {
                break;
            }
        }

        for (int i = 0; i < clazzs.size(); i++) {
            Field[] fields = clazzs.get(i).getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                //由字符串转换回对象对应的类型
                if (field != null) {
                    field.setAccessible(true);
                    field.set(obj, map.get(field.getName()));
                }
            }
        }
        return obj;
    }

    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        //获取关联的所有类，本类以及所有父类
        boolean ret = true;
        Class oo = obj.getClass();
        List<Class> clazzs = new ArrayList<Class>();
        while (ret) {
            clazzs.add(oo);
            oo = oo.getSuperclass();
            if (oo == null || oo == Object.class) {
                break;
            }
        }

        Map<String, Object> map = new HashMap<String, Object>();

        for (int i = 0; i < clazzs.size(); i++) {
            Field[] declaredFields = clazzs.get(i).getDeclaredFields();
            for (Field field : declaredFields) {
                int mod = field.getModifiers();
                //过滤 static 和 final 类型
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        }

        return map;
    }


    public static String map2String(Map map) {
        JSONObject jsonObject = JSONObject.fromObject(map);
        return jsonObject.toString();
    }

    public static JSONObject map2Json(Map map) {
        JSONObject jsonObject = JSONObject.fromObject(map);
        return jsonObject;
    }


    /**
     * 16进制颜色转RGB
     *
     * @param str
     * @return
     */
    public static Color conver2RGB(String str) {
        if (!(str.length() == 7)) {
            logger.error(str + "专程RGB颜色时异常");
            return null;
        } else {
            String str2 = str.substring(1, 3);
            String str3 = str.substring(3, 5);
            String str4 = str.substring(5, 7);
            int red = Integer.parseInt(str2, 16);
            int green = Integer.parseInt(str3, 16);
            int blue = Integer.parseInt(str4, 16);
            return new Color(red, green, blue);
        }
    }


    /**
     * unicode 转中文
     *
     * @param line
     * @return
     */
    public static String clearUnicode(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

        Matcher matcher = pattern.matcher(str);

        char ch;

        while (matcher.find()) {

            ch = (char) Integer.parseInt(matcher.group(2), 16);

            str = str.replace(matcher.group(1), ch + "");

        }

        return str;

    }


    public static byte[] charToByte(char c) {
        byte[] b = new byte[2];
        b[0] = (byte) ((c & 0xFF00) >> 8);
        b[1] = (byte) (c & 0xFF);
        return b;
    }
}
